//
//  NSObject+Addtionss.swift
//  CFUnion
//
//  Created by heew on 16/8/24.
//  Copyright © 2016年 heew. All rights reserved.
//

import UIKit
import Alamofire

extension NSObject {
    
    
    class var nameOfClass: String {
        return NSStringFromClass(self).components(separatedBy: ".").last! as String
    }
    
    func showToast(text: String,duration:TimeInterval = 2.0) {
        let _ =  APPToast(text: text,duration:duration)
    }

    
    /// 设置关联对象
    public func setAssociatedObject(obj:AnyObject,key:UnsafeRawPointer) {
        objc_setAssociatedObject(self, key, obj, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    }
    
    /// 获取关联对象
    public func associatedObjectForKey(key:UnsafeRawPointer) -> AnyObject? {
        return objc_getAssociatedObject(self, key) as AnyObject?
    }
    
    /// 去掉所有关联对象
    public func removeAssociatedObjects() {
        objc_removeAssociatedObjects(self)
    }
    
    /// 任何对象都可以发送网络请求
    public func GETRequestWith(urlString : YYURL,isShowHUD:Bool = true,timeoutInterval:TimeInterval = 30.0, success : ((AppResponse) ->Void)?, progress: ((Progress) -> Void)?=nil, failure: ((Error) ->Void)!)
    {
        return RequestWithUrlStringAndImage(urlString: urlString,isShowHUD: isShowHUD,timeoutInterval:timeoutInterval, success: success, progress: progress, failure: failure)
    }
    
    /// POST请求
    public func POSTRequestWith(urlString : YYURL, isShowHUD:Bool = true,success : ((AppResponse) ->Void)?, progress: ((Progress) -> Void)?=nil, failure: ((Error) ->Void)!)
    {
        return RequestWithUrlStringAndImage(urlString: urlString, isPost: true,isShowHUD: isShowHUD, success: success, progress: progress, failure: failure)
    }
    
    
    func postNotification(name:String,object:AnyObject? = nil,userInfo:[String:AnyObject]) {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: name), object: object, userInfo: userInfo)//postNotificationName(name, object: object,userInfo: userInfo )
    }
    
    func addNotificationObserver(selector:Selector,name:String?,object:AnyObject?) {
        NotificationCenter.default.addObserver(self, selector: selector, name: name.map { NSNotification.Name(rawValue: $0) }, object: object)
    }
    
    func removeNotificationObserver() {
        NotificationCenter.default.removeObserver(self)
    }
}
//MARK:私有方法
extension NSObject {
    
    fileprivate func RequestWithUrlStringAndImage(urlString : YYURL,isPost:Bool = false,isShowHUD:Bool, timeoutInterval:TimeInterval = 30.0, success : ((AppResponse) ->Void)?,progress:((Progress) -> Void)?, failure: ((Error) ->Void)? = nil) {
        
        let dic = urlString.queryDictionary
        
        // 打印url
        APPLog(message: "[\(self.classForCoder)]---------" + urlString.joinActionAndParams())
        
        if isShowHUD { BaseHUD.show() }
        
        let method = isPost ? HTTPMethod.post : .get
        Alamofire.request(urlString.action, method: method, parameters: dic, encoding: URLEncoding.default, headers: nil).responseData { (response) in
            BaseHUD.dismiss()
            if response.result.isSuccess {
                self.logResponse(data:response.data)
                success?(AppResponse(data: response.data))
            }else{
                failure?(response.result.error!)
            }
        }
    }
    
    fileprivate func logResponse(data: Data?) {
        guard let data = data else {return}
        #if DEBUG
        if let jsonString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
        {
            APPLog(message:jsonString)
        }
        #endif
    }
}

